#include <dlfcn.h>
#include <iostream>
#include <stdio.h>
#include "dll_test.h"
 
typedef Calculator* (*cal_def)();
// int Calculator::add(int a, int b) {
//     return 2;
// }
 

int main() {
    // 打开动态库
    void* handle = dlopen("./libcalculator.so", RTLD_LAZY);
    if (!handle) {
        std::cerr << "Error opening dynamic library: " << dlerror() << std::endl;
        return 1;
    }
    
    printf("--------------> 1\n");
    // 获取动态库中的函数指针
 
    cal_def exampleFunction = (cal_def)dlsym(handle, "createCalculator");
    printf("--------------> 2\n");
    if (!exampleFunction) {
        std::cerr << "Error finding symbol: " << dlerror() << std::endl;
        dlclose(handle);
        return 1;
    }
    printf("--------------> 4\n");
    const char* dlsym_error = dlerror();
    if (dlsym_error) {
        std::cerr << "无法找到动态库中的符号: " << dlsym_error << '\n';
        dlclose(handle);
        return 1;
    }   
    printf("--------------> 5\n");
    Calculator *exampleFunction1 =  exampleFunction();
    printf("--------------> 6\n");
    if(exampleFunction1 != nullptr)
    {
        printf("--------------> 7\n");
           // 调用动态库中的函数
        printf("-----> %d\n", exampleFunction1->add(1, 2));
    }
     

    // 关闭动态库
    dlclose(handle);

    return 0;
}

 